<!--
 * @Description: 
 * @Author: your name
 * @version: 
 * @Date: 2024-06-24 09:54:05
 * @LastEditors: your name
 * @LastEditTime: 2024-06-27 14:20:24
-->
<template>
  <a-card title="查看房户信息" style="width: 300px;pointer-events: all;">
    <span style="margin-right: 20px;">楼栋选择:</span>
    <a-select ref="select" v-model:value="selectBuild" style="width: 120px" :options="buildsOption"
        @change="handleChange"></a-select>
  </a-card>
</template>

<script setup>
import * as Cesium from 'cesium'
import {ref,onMounted,onBeforeUnmount} from 'vue'
import {getBuild,getHouse,getOneHouseInfo} from '@/api/api'
import * as turf from '@turf/turf'
import HtmlMarker from './Popup/popup'
import { useMapData } from '@/store'

const selectBuild=ref('')
const buildsOption=ref([])
const mapStore = useMapData()
// 获取viewer
const viewer = mapStore.Viewer
const popup=new HtmlMarker(viewer,{
  offset:[205,150]
})
// 注册屏幕空间事件
const handler=new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
onMounted(async () => {
  const buildInfo = await getBuild()
  if (buildInfo?.code === 200) {
    buildsOption.value = buildInfo.data.map(item => {
      return {
        value: item.id,
        label: item.name,
        polygon: item.polygon
      }
    })
  }
  initHandler()
})

onBeforeUnmount(()=>{
  popup && popup.removeMarker()
  if (houseList.length) {
    houseList.forEach(item => { viewer.scene.primitives.remove(item) })
  }
  houseList.length=0
  handler && screenEvent && handler.removeInputAction(screenEvent)
})

const houseList=[]
const colors = [
  "#99CCCC",
  "#66FF66",
  "#FF6666",
  "#00CCFF",
  "#00FF33",
  "#CC0000",
  "#CC00CC",
  "#CCFF00",
  "#0000FF",
];
const handleChange=async (e)=>{
  if (houseList.length) {
    houseList.forEach(item => { viewer.scene.primitives.remove(item) })
  }
  houseList.length=0
  popup && popup.removeMarker()
  const target = buildsOption.value.find(item => item.value === e)
  if (target){
    const { polygon } = target
    const center = turf.center(polygon)
    viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(
        ...center.geometry.coordinates,
        200
      ),
    });
    const param={
      id:e, noPage: 1
    }
    const res=await getHouse(param)
    if(res.code===200){
      res.data.forEach(item=>{
        let arr = item.polygon.coordinates[0].flat()
        let primitive = new Cesium.ClassificationPrimitive({
          geometryInstances: new Cesium.GeometryInstance({
            id: item.id,
            geometry: new Cesium.PolygonGeometry({
              polygonHierarchy: new Cesium.PolygonHierarchy(
                Cesium.Cartesian3.fromDegreesArray(arr)
              ),
              height: item.minHeight,
              extrudedHeight: item.maxHeight,
            }),
            attributes: {
              color: Cesium.ColorGeometryInstanceAttribute.fromColor(
                Cesium.Color.fromCssColorString(colors[item.id % 9]).withAlpha(
                  0.3
                )
              ),
            },
          }),
          classificationType: Cesium.ClassificationType.CESIUM_3D_TILE,
        });
        houseList.push(primitive)
        viewer.scene.primitives.add(primitive);
        // 注册鼠标事件
      })
    }
  }
}

let lastPick
let screenEvent
const initHandler=()=>{
  screenEvent=(e)=>{
    const position=viewer.scene.pickPosition(e.position);
    let pick = viewer.scene.pick(e.position)
    if (position && pick && pick.id){
      // 重复点击，不会重复发起请求
      if(lastPick && lastPick.id===pick.id){
        return
      }
      // 如果存在之前点击的图元，将颜色还原
      if(lastPick && lastPick.id){
        const lastAttributes = lastPick.primitive.getGeometryInstanceAttributes(lastPick.id)
        lastAttributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(
          Cesium.Color.fromCssColorString(colors[lastPick.id % 9]).withAlpha(0.3)
        )
      }
      const attributes = pick.primitive.getGeometryInstanceAttributes(pick.id)
      attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.YELLOW.withAlpha(0.88));
      lastPick=pick
      getOneHouseInfo({ id: pick.id }).then(res=>{
        if (res.code == 200){
          let houseInfo = res.data
          popup && popup.removeMarker()
          popup.changePosition(position)
          popup.addLabel(houseInfo)
        } 
      })
    }
  }
  handler && handler.setInputAction(screenEvent,Cesium.ScreenSpaceEventType.LEFT_CLICK)
}
</script>
<style scoped lang='less'>
</style>